package com.auerdi.ui.detail;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auerdi.GlideApp;
import com.auerdi.R;
import com.auerdi.dialog.CateGoryPinDialog;
import com.auerdi.dialog.CheckPinDialog;
import com.auerdi.dialog.WantPinDialog;
import com.auerdi.ui.detail.cutprice.child.view.ClockTextV2;
import com.auerdi.wxapi.WXEntryActivity;
import com.example.eggframe.GoHomeEvent;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.GoodLoveList;
import com.example.egghttp.retrofit.beans.banner.Prodetail;
import com.example.egghttp.retrofit.beans.banner.ProdictDetailContainer;
import com.example.egghttp.retrofit.beans.banner.ResultsData;
import com.example.egghttp.retrofit.beans.banner.ShopInfo;
import com.example.egghttp.retrofit.beans.banner.TeamResponce;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.example.egghttp.retrofit.beans.goods.WaitPing;
import com.example.egghttp.retrofit.params.CollageOrderCollectRequest;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class ADProductDetailFragment extends SwipeBackFragment {


    private static Product mProduct;
    @BindView(R.id.title_left)
    View titleLeft;
    Unbinder unbinder;
    @BindView(R.id.buynow)
    LinearLayout buynow;
    @BindView(R.id.price_tua)
    TextView priceTua;
    @BindView(R.id.market_price)
    TextView marketPrice;
    @BindView(R.id.price_tua_top)
    TextView priceTuaTop;
    @BindView(R.id.price_single)
    TextView priceSingle;
    @BindView(R.id.pin)
    TextView pin;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.guojia)
    ImageView guojia;
    @BindView(R.id.guojia_title)
    TextView guojiaTitle;
    @BindView(R.id.backhome)
    LinearLayout backhome;
    @BindView(R.id.like)
    LinearLayout like;
    @BindView(R.id.cusser)
    LinearLayout cusser;
    @BindView(R.id.groupbuy)
    LinearLayout groupbuy;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.aa)
    TextView aa;
    @BindView(R.id.pairtxt)
    TextView pairtxt;
    @BindView(R.id.bottonrecy)
    RecyclerView bottonrecy;
    @BindView(R.id.shopImg)
    ImageView shopImg;
    @BindView(R.id.shopName)
    TextView shopName;
    @BindView(R.id.shopNum)
    TextView shopNum;
    @BindView(R.id.goSHop)
    TextView goSHop;
    @BindView(R.id.tualist)
    RecyclerView tualist;
    @BindView(R.id.introText)
    TextView introText;
    @BindView(R.id.btnLike)
    ImageView btnLike;
    @BindView(R.id.goto_pin)
    Button gotoPin;
    @BindView(R.id.pin_circleView)
    ImageView pinCircleView;
    @BindView(R.id.pin_name)
    TextView pinName;
    @BindView(R.id.lack_people)
    TextView lackPeople;
    @BindView(R.id.lack_time)
    ClockTextV2 lackTime;
    @BindView(R.id.waitPin1)
    RelativeLayout waitPin1;
    @BindView(R.id.pin_circleView_2)
    ImageView pinCircleView2;
    @BindView(R.id.pin_name_2)
    TextView pinName2;
    @BindView(R.id.lack_people_2)
    TextView lackPeople2;
    @BindView(R.id.lack_time_2)
    ClockTextV2 lackTime2;
    @BindView(R.id.goto_pin_2)
    Button gotoPin2;
    @BindView(R.id.waitPin2)
    RelativeLayout waitPin2;
    private List<String> mInforList = new ArrayList<>();
    private List<Product> mEveryBodyLisy = new ArrayList<>();

    private String mSid;

    public static ADProductDetailFragment newInstance(Product product) {
        Bundle args = new Bundle();
        mProduct = product;
        ADProductDetailFragment fragment = new ADProductDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ad_fragment_product_detail, container, false);
        L.d("hcia", "view:" + view);
        View tpview = attachToSwipeBack(view);
        unbinder = ButterKnife.bind(this, tpview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        tualist.setLayoutManager(linearLayoutManager);
        tualist.setAdapter(new CommonAdapter<Product>(getActivity(), R.layout.item_home_love_v2, mEveryBodyLisy) {
            @Override
            protected void convert(ViewHolder viewHolder, final Product product, int position) {

                ImageView imgView = viewHolder.getView(R.id.img);
                ImageView gPic = viewHolder.getView(R.id.gpic);
                viewHolder.setText(R.id.title, product.getTitle());
                viewHolder.setText(R.id.gname, product.getBnProductGuojiaName());
                viewHolder.setText(R.id.stitle, product.getShareTitle());
                viewHolder.setText(R.id.apri, "¥" + product.getSuccessPrice());
                viewHolder.setText(R.id.bpri, "¥" + product.getMarkPrice());
                Picasso.get().load(product.getBnProductGuojia()).error(R.mipmap.logo).placeholder(R.mipmap.logo).fit().centerInside().into(gPic);

                GlideApp.with(viewHolder.getConvertView().getContext())
                        .load(product.getLunboImg())
                        .placeholder(R.mipmap.eptb)
                        .error(R.mipmap.pay_err)
                        .fitCenter()
                        .into(imgView);


                viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        EventBusActivityScope.getDefault((Activity) viewHolder.getConvertView().getContext()).post(ADProductDetailFragment.newInstance(product));


                    }
                });

            }
        });
        bottonrecy.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) {

            @Override
            public boolean canScrollVertically() {
                return false;
            }

        });

        bottonrecy.setAdapter(new CommonAdapter<String>(getActivity(), R.layout.item_detail_inforimg, mInforList) {


            @Override
            protected void convert(ViewHolder holder, final String item, final int outposition) {


                ImageView big = holder.getView(R.id.img);
                GlideApp.with(holder.getConvertView().getContext())
                        .load(item)
                        .placeholder(R.mipmap.eptb)
                        .error(R.mipmap.eptb)
                        .into(big);

            }
        });


        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                String bannStr = (String) path;
                GlideApp.with(getActivity())
                        .load(bannStr)
                        .placeholder(R.mipmap.epta)
                        .error(R.mipmap.epta)
                        .centerInside()
                        .into(imageView);
            }
        });

        marketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
        backhome.setOnClickListener(v -> EventBusActivityScope.getDefault(getActivity()).post(new GoHomeEvent()));
        buynow.setOnClickListener(v -> CateGoryPinDialog.newInstance(mProduct, Product.ZhiGouPrice).show(getFragmentManager(), ""));
        groupbuy.setOnClickListener(v -> CateGoryPinDialog.newInstance(mProduct, Product.TuanZhangPrice).show(getFragmentManager(), ""));
        cusser.setOnClickListener(v -> startActivity(new Intent(getActivity(), WXEntryActivity.class)));
        titleLeft.setOnClickListener(v -> pop());


//        gotoPin.setOnClickListener(v -> CateGoryPinDialog.newInstance(mProduct, Product.GroupPrice).show(getFragmentManager(), ""));


        return tpview;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        L.d("hcia", "onViewCreated:");
        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RetrofitClient.getPDAClient().create(AdService.class).collageCollect(new CollageOrderCollectRequest(mProduct.getId(), mProduct.getHuodongType(), mSid))              //获取Observable对象
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(

                                new Subscriber<BOb<ResultsData>>() {
                                    @Override
                                    public void onCompleted() {
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                    }

                                    @Override
                                    public void onNext(BOb<ResultsData> resultsDataBOb) {
                                        L.d("hcia", "resultsDataBOb.getBody().getIs_result():" + resultsDataBOb.getBody().getIs_result());
                                        String isResult = resultsDataBOb.getBody().getIs_result();
                                        btnLike.setImageResource(isResult.equals("0") ? R.mipmap.store_n : R.mipmap.store_r);
                                    }
                                }

                        );

            }
        });

        RetrofitClient.getPDAClient().create(AdService.class).goodsEverybodys()//大家都在團
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<GoodLoveList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<GoodLoveList> goodLoveListBOb) {
                        List<Product> bodyLsiy = goodLoveListBOb.getBody().getProLists();
                        mEveryBodyLisy.clear();
                        mEveryBodyLisy.addAll(bodyLsiy);
                        tualist.getAdapter().notifyDataSetChanged();

                    }
                });

        RetrofitClient.getPDAClient().create(AdService.class).collagePendingCollage(mProduct.getId(), "0", "2", "1")//
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(

                        new Subscriber<BOb<TeamResponce>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BOb<TeamResponce> teamResponceBOb) {

                                List<WaitPing> teamList = teamResponceBOb.getBody().getTeam_list();

                                if (teamList.size() == 0) {
                                    waitPin1.setVisibility(View.GONE);
                                    waitPin2.setVisibility(View.GONE);

                                } else if (teamList.size() == 1) {

                                    waitPin1.setVisibility(View.VISIBLE);
                                    waitPin2.setVisibility(View.GONE);

                                    WaitPing pinOne = teamList.get(0);

                                    GlideApp.with(getActivity())
                                            .load(pinOne.getAvatar_url())
                                            .placeholder(R.mipmap.eptb)
                                            .error(R.mipmap.eptb)
                                            .into(pinCircleView);

                                    pinName.setText(pinOne.getNick());
                                    lackPeople.setText("还差" + pinOne.getLack_people() + "人成团");

                                    Long tsLong = System.currentTimeMillis() / 1000;
//                                    L.d("hcia", "tsLong:" + tsLong);
//                                    L.d("hcia", "pinOne.getDifference_second():" + pinOne.getDifference_second());
//                                    String tsLongStr =  tsLong.intValue();

                                    lackTime.setCondownSecond(Integer.parseInt(pinOne.getDifference_second()), tsLong.intValue());

                                    gotoPin.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            WantPinDialog.newInstance(mProduct, Product.GroupPrice).show(getFragmentManager(), "");

                                        }
                                    });


//                                    gotoPin.setOnClickListener(v ->
//
//
//
////                                            CheckPinDialog.newInstance(mProduct, Product.GroupPrice).show(getFragmentManager(), "")
//
//                                    );

//                                    lackTime
                                } else if (teamList.size() == 2) {
                                    waitPin1.setVisibility(View.GONE);
                                    waitPin2.setVisibility(View.VISIBLE);

                                    WaitPing pinOne = teamList.get(0);
                                    WaitPing pinTwo = teamList.get(1);

                                    mProduct.setTeam_start_id(pinOne.getTeam_start_id());

                                    gotoPin.setOnClickListener(v -> {
                                        mProduct.setTeam_start_id(pinOne.getTeam_start_id());
                                        CheckPinDialog.newInstance(mProduct, Product.GroupPrice).show(getFragmentManager(), "");
                                    });


                                    gotoPin2.setOnClickListener(v -> {

                                        mProduct.setTeam_start_id(pinTwo.getTeam_start_id());

                                        CheckPinDialog.newInstance(mProduct, Product.GroupPrice).show(getFragmentManager(), "");

                                    });

                                }

                            }
                        }

                );

        RetrofitClient.getPDAClient().create(AdService.class).goodDetail(mProduct.getId(), mProduct.getHuodongType())
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<ProdictDetailContainer>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<ProdictDetailContainer> prodictDetailContainerBOb) {
                        Prodetail proDetail = prodictDetailContainerBOb.getBody().getPro_details();


                        btnLike.setImageResource(proDetail.getIs_collected().equals("0") ? R.mipmap.store_n : R.mipmap.store_r);
                        mSid = proDetail.getSid();
                        mSid = proDetail.getSid();
                        introText.setText(proDetail.getIntro());

                        RetrofitClient.getClient().create(AdService.class).shopShopinfos(proDetail.getSid())
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(
                                        new Subscriber<BOb<ShopInfo>>() {
                                            @Override
                                            public void onCompleted() {

                                            }

                                            @Override
                                            public void onError(Throwable e) {

                                            }

                                            @Override
                                            public void onNext(BOb<ShopInfo> shopInfoBOb) {


                                                shopName.setText(shopInfoBOb.getBody().getShop_info().getShop_name());
                                                shopNum.setText("售出商品" + shopInfoBOb.getBody().getShop_info().getSell_count() + "件");
                                                GlideApp.with(getActivity())
                                                        .load(shopInfoBOb.getBody().getShop_info().getShop_logo())
                                                        .placeholder(R.mipmap.eptb)
                                                        .error(R.mipmap.eptb)
                                                        .into(shopImg);

                                            }
                                        }

                                );

                        List<String> headdatas = proDetail.getInfo();

                        mInforList.clear();
                        mInforList.addAll(headdatas);
                        bottonrecy.getAdapter().notifyDataSetChanged();

                        banner.setImages(headdatas);
                        banner.start();

                        Observable.just(proDetail.getMark_price())
                                .map(s -> "¥" + s)
                                .subscribe(s -> {
                                    marketPrice.setText(s);
                                });

                        Observable.just(proDetail.getSuccess_price())
                                .map(s -> "¥" + s)
                                .subscribe(s -> priceTua.setText(s));


                        priceTuaTop.setText(proDetail.getSuccess_price());
                        priceSingle.setText("¥" + proDetail.getPrice());
                        mProduct.setDerict_price(proDetail.getPrice());


                        title.setText(proDetail.getTitle());
                        pin.setText("已拼" + proDetail.getSuccess_num() + "件");
                        guojiaTitle.setText(proDetail.getBn_product_guojia_name() + " " + proDetail.getBn_product_from_name() + " " + proDetail.getHuodongType());
                        pairtxt.setText(proDetail.getHuodongType());
                        Picasso.get().load(proDetail.getBn_product_guojia()).error(R.mipmap.logo).placeholder(R.mipmap.logo).fit().centerInside().into(guojia);
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        hideSoftInput();
    }
}
